<template>
  <div class="xd-LearningHome-CourseIntroduction p_10">
    <el-card
      shadow="hover"
      v-show="detail.curriculumId"
    >
      <header>
        <img
          class="cover"
          :src="detail.imgUrl?detail.imgUrl:defaultImg"
        />
        <div class="course-info">
          <p
            class="text_color_333333 title"
            v-text="detail.curriculumTitle"
          ></p>
          <div class="text_color_999999 text_size_7 desc"></div>
          <table
            border="0"
            cellpadding="0"
            cellspacing="0"
            class="xt_table"
            style="margin-top:1vw"
          >
            <tr>
              <td
                class="text_color_429688"
                v-text="detail.curriculumTimeLong"
              ></td>
              <td
                class="text_color_429688"
                v-text="detail.studyNum+'人'"
              ></td>
              <!-- <td
                class="text_color_429688"
                v-text="detail.curriculumPoints"
              ></td> -->
              <td
                class="text_color_429688"
                v-text="detail.expirationDate"
              ></td>
              <td rowspan="2">
                <el-button @click="showStudyDetail">学习详情</el-button>
              </td>
            </tr>
            <tr>
              <td class="text_color_999999">学时（分钟）</td>
              <td class="text_color_999999">学习人数</td>
              <!-- <td class="text_color_999999">学分</td> -->
              <td class="text_color_999999">截止期限</td>
            </tr>
          </table>
        </div>
      </header>

      <el-collapse
        class="m_t_15"
        v-model="activeName"
      >
        <el-collapse-item
          title="内容简介"
          name="1"
        >
          <p class="row-title">简介内容</p>
          <pre
            class="richtext-content"
            v-html="detail.curriculumIntroduction"
          ></pre>
        </el-collapse-item>

        <el-collapse-item
          title="章节目录"
          name="2"
        >
          <div
            class="list-container"
            v-for="(item, idx) in detail.curriculumChapterList"
            :key="'curriculumChapter' + idx"
          >
            <p
              class="row-title"
              v-text="item.chapterTitle"
            ></p>
            <div
              class="cell_panel"
              v-for="(courseware, cIndex) in item.coursewareList"
              :key="'courseware' + cIndex"
            >
              <div
                class="title"
                v-text="courseware.coursewareName"
              ></div>
              <div class="label">
                <template v-if="courseware.isCompleted===1">
                  <el-button
                    :type="courseware.isCompleted===1?'success':''"
                    size="mini"
                    @click="startLearning(idx, cIndex, courseware)"
                  >已完成</el-button>
                </template>
                <template v-else>
                  <el-button
                    size="mini"
                    type="primary"
                    style="color:white;"
                    @click="startLearning(idx, cIndex, courseware)"
                  >开始学习</el-button>
                </template>
              </div>
            </div>
          </div>
        </el-collapse-item>

        <el-collapse-item
          title="学习测试"
          name="4"
        >
          <el-button
            v-for="(item, idx) in practiceList"
            :key="'practice' + idx"
            size="mini"
            type="primary"
            style="color:white; margin-bottom: 10px; margin-left: 10px;"
            @click="goPractice(item)"
          >{{item.paperTitle}}</el-button>
          <!-- <ul>
            <li
              v-for="(item, idx) in practiceList"
              :key="'practice' + idx"
              @click="goPractice(item)"
            >{{item.paperTitle}}</li>
          </ul> -->
        </el-collapse-item>

        <el-collapse-item
          title="学习心得"
          name="4"
        >
          <ul class="study-note-list">
            <li
              v-for="(item, idx) in studyNoteList"
              :key="'studyNote' + idx"
              @click="goStudyNode(item)"
              class="study-note-cell"
            >
              <span class="note-title">{{item.title}}</span>
              <span class="note-time">{{item.createTime}}</span>
            </li>
          </ul>
          <el-form
            :model="noteForm"
            status-icon
            ref="noteForm"
            label-width="70px"
            label-position="left"
            class="study-note-form"
          >
            <el-form-item
              label="标题"
              prop="title"
            >
              <el-input
                type="text"
                v-model="noteForm.title"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="内容"
              prop="content"
            >
              <el-input
                type="textarea"
                v-model="noteForm.content"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="submitStudyNote"
              >提交</el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>

        <el-collapse-item
          title="课程评论"
          name="3"
        >
          <MyComments
            :commentsInfo="detail.curriculumChapterCommentList"
            :loading="loading"
            :noMore="noMore"
          ></MyComments>
        </el-collapse-item>
      </el-collapse>

      <el-dialog :visible.sync="receiveDetailVisible">
        <!-- <template>
          <div style=" height: 60vh;overflow-y: auto;overflow-x:hidden;">
            <h4>未学习（{{receiveListNot.length}}）</h4>
            <el-row :gutter="28">
              <el-col
                v-for="(item, idx) in receiveListNot"
                :key="'dept' + idx"
                :span="4"
              >
                <div
                  class="grid-content bg-primary bg-primary-light"
                  v-if="item.completeStatus==-1"
                >{{item.userName}}</div>
              </el-col>
            </el-row>
            <h4>学习中（{{receiveListInProgress.length}}）</h4>
            <el-row :gutter="28">
              <el-col
                v-for="(item, idx) in receiveListInProgress"
                :key="'dept' + idx"
                :span="4"
              >
                <div
                  class="grid-content bg-primary bg-primary-light1"
                  v-if="item.completeStatus==0"
                >{{item.userName}}</div>
              </el-col>
            </el-row>
            <h4>已完成（{{receiveListCompleted.length}}）</h4>
            <el-row :gutter="28">
              <el-col
                v-for="(item, idx) in receiveListCompleted"
                :key="'dept' + idx"
                :span="4"
              >
                <div
                  class="grid-content bg-primary"
                  v-if="item.completeStatus==1"
                >{{item.userName}}</div>
              </el-col>
            </el-row>
          </div>
        </template> -->
        <div slot="title">
          <div
            class="dialog-back"
            v-show="deptHistory.length > 1"
            @click="dialogBack"
          >&lt;&nbsp;&nbsp;返回</div>
        </div>
        <template>
          <div style=" height: 60vh;overflow-y: auto;overflow-x:hidden;">
            <h4>未学习</h4>
            <el-row :gutter="28">
              <el-col
                v-for="(item, idx) in receiveListIsDeptNotRead"
                :key="'dept' + idx"
                :span="4"
              >
                <div
                  class="grid-content bg-primary dept"
                  :class="{'bg-primary-light': item.readCount !== item.userCount}"
                  @click="fetchReceiveDetail(item)"
                >
                  {{item.dept_name}}
                  <div>({{item.readCount}}/{{item.userCount}})</div>
                </div>
              </el-col>
              <el-col
                v-for="(item, idx) in receiveListNotDeptNotRead"
                :key="'dept' + idx"
                :span="4"
              >
                <div
                  class="grid-content bg-primary"
                  :class="{'bg-primary-light': !item.readFlag}"
                >{{item.user_name}}</div>
              </el-col>
            </el-row>
            <h4>已学习</h4>
            <el-row :gutter="28">
              <el-col
                v-for="(item, idx) in receiveListIsDeptIsRead"
                :key="'dept' + idx"
                :span="4"
              >
                <div
                  class="grid-content bg-primary dept" style="background: #07806d;"
                  :class="{'bg-primary-light': item.readCount !== item.userCount}"
                  @click="fetchReceiveDetail(item)"
                >
                  {{item.dept_name}}
                  <div>({{item.readCount}}/{{item.userCount}})</div>
                </div>
              </el-col>
              <el-col
                v-for="(item, idx) in receiveListNotDeptIsRead"
                :key="'dept' + idx"
                :span="4"
              >
                <div
                  class="grid-content bg-primary" style="background: #07806d;"
                  :class="{'bg-primary-light': !item.readFlag}"
                >{{item.user_name}}</div>
              </el-col>
            </el-row>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
  import defaultImg from '@/assets/imgs/default_img.jpg'
  const MyComments = () => import('../../../components/MyComments');

  export default {
    name: 'CourseIntroduction',
    components: {
      MyComments
    },
    data() {
      return {
        defaultImg: defaultImg,
        receiveDetailVisible: false,
        receiveList: [],
        loading: false,
        activeName: ['1', '2', '3', '4'],
        detail: {},
        practiceList: [],
        tid: 0,
        studyNoteList: [],
        noteForm: {
          title: '',
          content: ''
        },
        deptHistory: [],
        receiveParams: { deptids: '' } //初始接收详情参数
      };
    },
    computed: {
      noMore() {
        return this.count >= 20;
      },
      disabled() {
        return this.loading || this.noMore;
      },
      activeCurriculumId() {
        return this.$store.state.activeCurriculumId;
      },
      receiveListNot: function() {
        return this.receiveList.filter(function(item) {
          return item.completeStatus == -1;
        });
      },
      receiveListInProgress: function() {
        return this.receiveList.filter(function(item) {
          return item.completeStatus == 0;
        });
      },
      receiveListCompleted: function() {
        return this.receiveList.filter(function(item) {
          return item.completeStatus == 1;
        });
      },
      //
      receiveListIsDeptList: function() {
        return this.receiveList.filter(function(item) {
          return item.is_dept === 1;
        });
      },
      receiveListIsDeptIsRead: function() {
        return this.receiveList.filter(function(item) {
          return item.is_dept === 1 && item.readCount === item.userCount;
        });
      },
      receiveListIsDeptNotRead: function() {
        return this.receiveList.filter(function(item) {
          return item.is_dept === 1 && item.readCount !== item.userCount;
        });
      },
      receiveListNotDeptNotRead: function() {
        return this.receiveList.filter(function(item) {
          return item.is_dept != 1 && item.readFlag != 1;
        });
      },
      receiveListNotDeptIsRead: function() {
        return this.receiveList.filter(function(item) {
          return item.is_dept != 1 && item.readFlag === 1;
        });
      }
    },
    watch: {
      activeCurriculumId(newValue, oldValue) {
        if (newValue !== oldValue) {
          this.tid = newValue;
          this.fetchDetail();
        }
      }
    },
    created() {
      this.tid = this.$route.query.tid;
      this.fetchDetail();
      this.fetchPracticeList();
      this.browse();
      this.fetchStudyNoteList();
    },
    // mounted() {
    //   for (let index = 0; index < 5; index++) {
    //     this.comments.push({
    //       id: index,
    //       name: '张三' + index,
    //       avatar: '',
    //       content: '为把学习贯彻习近平新时代中国特色社会主义思想进一步引向深入，根据党中央要求，中央宣传部组织编写了《习近平新时代中国特色社会主义思想学习纲要》（以下简称《纲要》）。党中央认为，《纲要》对习近平新时代中国特色社会主义思想作了全面系统阐述，有助于更好地理解把握这一思想的基本精神、基本内容、基本要求。党中央同意印发《纲要》（由中央宣传部统一印发），作为广大干部群众深入学习领会习近平新时代中国特色社会主义思想的重要辅助读物。',
    //       date: new Date().toLocaleString()
    //     });
    //   }
    // },
    methods: {
      // handleClick(tab, event) {
      //   if (parseInt(tab.index, 10) === 3) {
      //     if (!this.practiceList.length) {
      //       this.fetchPracticeList()
      //     }
      //   }
      // },
      calcTimeLong(value) {
        // 保留一位小数向上取整
        let result = Math.ceil((value * 10) / 60);
        return result / 10;
      },
      // load() {
      // console.log(this.count)
      // this.loading = true

      // setTimeout(() => {
      //   for (let index = this.count; index < this.count + 5; index++) {
      //     this.comments.push({
      //       id: index,
      //       name: '张三' + index,
      //       avatar: '',
      //       content: '为把学习贯彻习近平新时代中国特色社会主义思想进一步引向深入，根据党中央要求，中央宣传部组织编写了《习近平新时代中国特色社会主义思想学习纲要》（以下简称《纲要》）。党中央认为，《纲要》对习近平新时代中国特色社会主义思想作了全面系统阐述，有助于更好地理解把握这一思想的基本精神、基本内容、基本要求。党中央同意印发《纲要》（由中央宣传部统一印发），作为广大干部群众深入学习领会习近平新时代中国特色社会主义思想的重要辅助读物。',
      //       date: new Date().toLocaleString()
      //     })
      //   }
      //   this.loading = false
      //   this.count += 5
      // }, 2000)
      // },
      startLearning(index, coursewareIndex, courseware) {
         if(index > 0 && courseware.isCompleted != 1){
           const arr = this.detail.curriculumChapterList[index-1].coursewareList;
           for (let i = 0; i < arr.length; i++) {
             if(arr[i].isCompleted != 1){
               this.$message.error('请按顺序完成章节学习');
               return;
             }
           }
         }

        utils.setItem('startLearning', this.detail.curriculumChapterList[index]);
        this.$router.push({
          path: '/LearningHome/Learning/VideoCourse',
          query: {
            tid: this.tid,
            coursewareIndex: coursewareIndex,
            coursewareId: courseware.coursewareId,
            curriculumId: this.detail.curriculumId, // 课程id
            curriculumTitle: this.detail.curriculumTitle, // 课程名称
            isCompleted: courseware.isCompleted // 课件完成状态
          }
        });
        // this.$router.push('/LearningHome/Learning/VideoCourse')
        // switch (this.courseInfo.chapterType) {
        //   case 'video':
        //     this.$router.push('/LearningHome/Learning/VideoCourse')
        //     break;
        // }
      },
      goPractice(item) {
        utils.setItem('ExamInstructionsPaperInfo', item);
        this.$router.push({ path: '/LearningHome/OnlineExams/ExamInstructions', query: { examType: 2 } });
      },
      fetchDetail() {
        let loadingInstance = this.Loading.service({
          fullscreen: true,
          lock: true,
          text: '拼命加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        utils.post(
          '/curriculum/get',
          {
            curriculumId: this.tid
          },
          (res) => {
            loadingInstance.close();
            if (res.success) {
              this.detail = res.data;
            }
          }
        );
      },
      fetchPracticeList() {
        utils.post(
          '/curriculum/curriculumTestList',
          {
            curriculumId: this.tid
          },
          (res) => {
            if (res.success) {
              this.practiceList = res.data.rows;
            }
          }
        );
      },
      browse() {
        utils.post('/curriculum/browse', {
          curriculumId: this.tid
        });
      },
      fetchStudyNoteList() {
        // const list = []
        // for (var i = 0; i < 10; i++) {
        //   list.push({
        //     id: i,
        //     title: 'title' + i,
        //     createTime: '2019-12-07'
        //   })
        // }
        // this.studyNoteList = list
        // return
        utils.post(
          'curriculum/curriculumStudyNotes/list',
          {
            curriculumId: this.tid
          },
          (res) => {
            if (res.success) {
              this.studyNoteList = res.data;
            }
          }
        );
      },
      goStudyNode(item) {
        this.$router.push({
          path: '/LearningHome/Learning/StudyNote',
          query: {
            tid: item.id
          }
        });
      },
      submitStudyNote() {
        if (!this.noteForm.title || !this.noteForm.content) {
          this.$message.error('请填写完整的心得信息');
          return;
        }
        utils.post(
          'curriculum/curriculumStudyNotes/add',
          {
            curriculumId: this.tid,
            title: this.noteForm.title,
            content: this.noteForm.content
          },
          (res) => {
            if (res.success) {
              this.fetchStudyNoteList();
              this.resetForm('noteForm');
            }
          }
        );
      },
      // submitForm(formName) {
      //   this.$refs[formName].validate((valid) => {
      //     if (valid) {
      //       alert('submit!');
      //     } else {
      //       console.log('error submit!!');
      //       return false;
      //     }
      //   });
      // },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      //课程学习详情
      showStudyDetail() {
        this.fetchReceiveDetail(this.receiveParams);
      },
      fetchReceiveDetail(params, isBack) {
        let loadingInstance = this.Loading.service({
          fullscreen: true,
          lock: true,
          text: '拼命加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        const deptids = params.dept_id || '';
        utils.post(
          'curriculum/studyCurriculumDetail  ',
          {
            curriculumId: this.detail.curriculumId,
            deptids: deptids
          },
          (res) => {
            loadingInstance.close();
            this.receiveDetailVisible = true;
            if (res.success) {
              this.receiveList = res.data;
              console.log(this.receiveList);
              if (!isBack) {
                this.deptHistory.unshift(params);
              }
            }
          }
        );
      },
      dialogBack() {
        this.deptHistory.shift();
        this.fetchReceiveDetail(this.deptHistory[0], true);
      },
      //课程学习详情弃用
      showStudyDetail_del() {
        let loadingInstance = this.Loading.service({
          fullscreen: true,
          lock: true,
          text: '拼命加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        utils.post(
          'curriculum/queryStudyDetail',
          {
            curriculumId: this.detail.curriculumId
          },
          (res) => {
            loadingInstance.close();
            if (res.success) {
              this.receiveList = res.data.receiveList;
              //this.deptList=res.data.deptList
              this.receiveDetailVisible = true;
            }
          }
        );
      }
    }
  };
</script>
<style lang="less">
  @primary-color: #cb2c21;
  @bg-light-color: #de1632;
  @bg-light-color1: #767609;

  .xd-LearningHome-CourseIntroduction {
    @tabs_color: #cb2c21;
    .el-card__body header {
      display: flex;
      .cover {
        display: flex;
        width: 200px;
        min-width: 200px;
        height: 125px;
      }

      .course-info {
        margin-left: 34px;
        margin-top: 0.57vw;
        display: flex;
        flex-direction: column;
        .title {
          font-size: 18px;
          font-weight: bold;
        }
      }

      .xt_table {
        tr {
          height: 1.8vw;
        }
        td {
          font-size: 16px;
        }
      }
    }
    .dialog-back {
      color: @primary-color;
      cursor: pointer;
    }
    .el-collapse-item__header {
      font-size: 18px;
      font-weight: normal;
      letter-spacing: 0px;
      color: #cb2c21;
      font-weight: bold;

      .el-icon-arrow-right {
        display: none;
      }
    }
    .el-collapse-item__header.is-active {
      border-bottom-color: #ebeef5;
    }

    .el-collapse-item__content {
      padding-top: 20px;
    }

    .study-note-list {
      .study-note-cell {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        .note-time {
          color: #999999;
        }
      }
    }

    .study-note-form {
      margin-top: 30px;
    }

    .el-col {
      border-radius: 4px;
      color: #ffffff;
      text-align: center;
      margin-bottom: 20px;
    }

    .bg-primary {
      background: @primary-color;
    }
    .bg-primary-light {
      background: @bg-light-color;
    }
    .bg-primary-light1 {
      background: @bg-light-color1;
    }

    .grid-content {
      border-radius: 4px;
      min-height: 30px;
      line-height: 30px;
      &.dept {
        line-height: 1;
        padding: 10px 0;
        cursor: pointer;
      }
    }
  }
</style>
